﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Entity;

namespace SalesVMT
{
    public partial class frmReceipt : Form
    {
        DialogResult dlgResult;
        ReceiptInfo receiptinf;
        private string keyword = "";
        public frmReceipt(int _Receipt_ID)
        {
            InitializeComponent();
            label6.Visible = false;
            txtTotal.Visible = false;
            receiptinf = new ReceiptInfo();
            lblNo.Text = UISetting.AutoFillReceiptCode();
            mtxReceiptDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            DisplayFrame();
            receiptinf.Receipt_ID = _Receipt_ID;
            if (_Receipt_ID > 0)
            {
                receiptinf = ReceiptDB.GetInfo(_Receipt_ID, "NCC");

                InfoToForm();
                LoadList();
                btnSave.Enabled = false;
            }
            TotalRowsPrice();
            this.KeyPreview = true;
            dlgResult = DialogResult.Cancel;

        }
        private void FormToInfo()
        {
            receiptinf.Receipt_Code = lblNo.Text;
            receiptinf.Receipt_Date = DateTime.ParseExact(mtxReceiptDate.Text, "dd/MM/yyyy", null);
            receiptinf.Receipt_ProviderID = Convert.ToInt32(lblProvider.Tag);
            receiptinf.Receipt_UsersID = UsersDB.GetInfoByUsersName(Program.strUserName).Users_ID;
            receiptinf.Receipt_Sender = txtSender.Text;
            receiptinf.Receipt_TotalPrice = Convert.ToDecimal(txtTotalPrice.Text);
            receiptinf.Receipt_TotalDownPrice = Convert.ToDecimal(txtTotalDownPrice.Text);
            receiptinf.Receipt_TotalVAT = Convert.ToDecimal(txtTotalVAT.Text);
            receiptinf.Receipt_Total = Convert.ToDecimal(txtTotal.Text);
            receiptinf.Receipt_Remaining = Convert.ToDecimal(txtRemaining.Text);
            receiptinf.Receipt_Debit = Convert.ToDecimal(txtDebit.Text);
            receiptinf.Receipt_Type = "NCC";
            receiptinf.Receipt_Status = "";
        }
        private void InfoToForm()
        {
            lblNo.Text = receiptinf.Receipt_Code;
            mtxReceiptDate.Text = Convert.ToDateTime(receiptinf.Receipt_Date).ToString("dd/MM/yyyy");
            lblProvider.Tag = receiptinf.Receipt_ProviderID;
            lblProvider.Text = ProviderDB.GetInfo(Convert.ToInt32(lblProvider.Tag)).Provider_Name.ToUpper();
            txtSender.Text = receiptinf.Receipt_Sender;
            txtRemaining.Text = Convert.ToDecimal(receiptinf.Receipt_Remaining).ToString("#,##0");

            txtDebit.Text = Convert.ToDecimal(receiptinf.Receipt_Debit).ToString("#,##0");
        }
        private void DisplayFrame()
        {
            UISetting.AddColumn(ref dgvList1, "Item_ID", "Khóa", "", 1, false, true);
            UISetting.AddColumn(ref dgvList1, "RowNumber", "STT", "C", 35, true, true);
            UISetting.AddColumn(ref dgvList1, "Item_Code", "Mã HH", "", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Item_Name", "Tên HH", "", 180, true, true);
            UISetting.AddColumn(ref dgvList1, "CalculationUnit_Name", "ĐVT", "C", 60, true, true);
            UISetting.AddColumn(ref dgvList1, "Quantity", "SL", "C", 45, true, false);
            UISetting.AddColumn(ref dgvList1, "Price", "Đơn giá", "R", 90, true, false);
            UISetting.AddColumn(ref dgvList1, "DownPrice", "Giảm(%)", "R", 60, true, false);

            DataGridViewComboBoxColumn cboColumn = new DataGridViewComboBoxColumn();
            cboColumn.HeaderText = "VAT(%)";
            cboColumn.Name = "VAT";
            cboColumn.Width = 50;
            dgvList1.Columns.Add(cboColumn);
            LoadVAT(ref cboColumn);

            UISetting.AddColumn(ref dgvList1, "Total", "Thành tiền", "R", 95, true, true);

            DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
            buttonColumn.HeaderText = "Lệnh";
            buttonColumn.Name = "Control";
            buttonColumn.Text = "Xóa";
            buttonColumn.Width = 60;
            buttonColumn.UseColumnTextForButtonValue = true;
            dgvList1.Columns.Add(buttonColumn);

            dgvList1.CellClick += new DataGridViewCellEventHandler(dgvList1_CellClick);
        }
        private void LoadList()
        {
            DataTable _dt = ReceiptDetailsDB.GetAllByReceipt(receiptinf.Receipt_ID).Tables[0];
            int n = _dt.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                dgvList1.Rows.Insert(i, 1);
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
                dgvList1.Rows[i].Cells["Item_ID"].Value = _dt.Rows[i]["Item_ID"].ToString();
                dgvList1.Rows[i].Cells["Item_Code"].Value = _dt.Rows[i]["Item_Code"].ToString();
                dgvList1.Rows[i].Cells["Item_Name"].Value = _dt.Rows[i]["Item_Name"].ToString();
                dgvList1.Rows[i].Cells["CalculationUnit_Name"].Value = _dt.Rows[i]["CalculationUnit_Name"].ToString();
                dgvList1.Rows[i].Cells["Quantity"].Value = _dt.Rows[i]["ReceiptDetails_Quantity"].ToString();
                dgvList1.Rows[i].Cells["Price"].Value = Convert.ToDecimal(_dt.Rows[i]["ReceiptDetails_Price"]).ToString("#,##0");
                dgvList1.Rows[i].Cells["DownPrice"].Value = Convert.ToDecimal(_dt.Rows[i]["ReceiptDetails_DownPrice"]).ToString("N");
                dgvList1.Rows[i].Cells["VAT"].Value = Convert.ToInt32(_dt.Rows[i]["ReceiptDetails_VAT"]);
                dgvList1.Rows[i].Cells["Total"].Value = Convert.ToDecimal(_dt.Rows[i]["ReceiptDetails_Total"]).ToString("#,##0");
            }
        }

        private ReceiptDetailsInfo[] ReadReceiptDetails()
        {
            int n = dgvList1.Rows.Count;
            if (n > 0)
            {
                ReceiptDetailsInfo[] tracks = new ReceiptDetailsInfo[n];
                for (int i = 0; i < n; i++)
                {
                    tracks[i] = new ReceiptDetailsInfo();
                    tracks[i].ReceiptDetails_ItemID = Convert.ToInt32(dgvList1.Rows[i].Cells["Item_ID"].Value);
                    tracks[i].ReceiptDetails_Quantity = Convert.ToInt32(dgvList1.Rows[i].Cells["Quantity"].Value);
                    tracks[i].ReceiptDetails_Price = Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value);
                    tracks[i].ReceiptDetails_DownPrice = Convert.ToDecimal(dgvList1.Rows[i].Cells["DownPrice"].Value);
                    tracks[i].ReceiptDetails_VAT = Convert.ToInt32(dgvList1.Rows[i].Cells["VAT"].Value);
                    tracks[i].ReceiptDetails_Total = Convert.ToDecimal(dgvList1.Rows[i].Cells["Total"].Value);
                }
                return tracks;
            }
            else
            {
                return null;
            }
        }
        private bool CheckValid()
        {
            if (Convert.ToInt32(lblProvider.Tag) == 0)
            {
                MessageBox.Show("Chưa chọn nhà cung cấp! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (!CheckTextValid.IsNumeric(txtRemaining.Text))
            {
                MessageBox.Show("Dư nợ đầu kỳ không hợp lệ! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtRemaining.Focus();
                txtRemaining.Text = "0.0";
                return false;
            }
            if (UISetting.GetDate(mtxReceiptDate.Text) == DateTime.MinValue)
            {
                MessageBox.Show("Ngày nhập không hợp lệ! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                mtxReceiptDate.Focus();
                return false;
            }


            return true;
        }


        public void LoadVAT(ref DataGridViewComboBoxColumn box)
        {
            DataTable dt = new DataTable();
            DataColumn dcol = null;
            dcol = new DataColumn("ID", typeof(int));
            dt.Columns.Add(dcol);
            dcol = new DataColumn("NAME", typeof(string));
            dt.Columns.Add(dcol);

            DataRow dr = dt.NewRow();
            dr["ID"] = 0;
            dr["NAME"] = "0";
            dt.Rows.InsertAt(dr, 0);

            dr = dt.NewRow();
            dr["ID"] = 5;
            dr["NAME"] = "5";
            dt.Rows.InsertAt(dr, 1);

            dr = dt.NewRow();
            dr["ID"] = 10;
            dr["NAME"] = "10";
            dt.Rows.InsertAt(dr, 2);

            box.ValueMember = "ID";
            box.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            box.DisplayMember = "NAME";
            box.DataSource = dt;
        }
        void dgvList1_CellSelectedIndexChange(object sender, DataGridViewCellEventArgs e)
        {
            //Kiểm tra xóa rows
            if (e.RowIndex < 0 || e.ColumnIndex !=
                    dgvList1.Columns["Control"].Index) return;
            dgvList1.Rows.RemoveAt(e.RowIndex);
            //Tính lại tổng tiền sau khi xóa
            TotalRowsPrice();
            //Sắp xếp lại thứ tự
            for (int i = 0; i < dgvList1.Rows.Count; i++)
            {
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
            }
        }

        void dgvList1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Kiểm tra xóa rows
            if (e.RowIndex < 0 || e.ColumnIndex !=
                    dgvList1.Columns["Control"].Index) return;
            dgvList1.Rows.RemoveAt(e.RowIndex);
            //Tính lại tổng tiền sau khi xóa
            TotalRowsPrice();
            //Sắp xếp lại thứ tự
            for (int i = 0; i < dgvList1.Rows.Count; i++)
            {
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
            }
        }



        private void btnFindProvoder_Click(object sender, EventArgs e)
        {
            frmProviderList f = new frmProviderList(true);
            f.ShowDialog(this);
            if (Convert.ToInt32(f.Provider_ID) > 0)
            {
                lblProvider.Tag = Convert.ToInt32(f.Provider_ID);
                lblProvider.Text = f.Provider_Name.ToUpper();

                DataTable _dt = ReceiptDB.GetProviderDebit(Convert.ToInt32(f.Provider_ID)).Tables[0];
                if (_dt.Rows[0]["Debit"] != DBNull.Value)
                    txtDebit.Text = Convert.ToDecimal(_dt.Rows[0]["Debit"]).ToString("#,##0");


                TotalRowsPrice();
            }
        }

        private void btnFindItem_Click(object sender, EventArgs e)
        {
            frmItemList f = new frmItemList(true, keyword);
            f.ShowDialog(this);
            int n = dgvList1.Rows.Count;

            if (f.Item_ID > 0)
            {
                //Kiểm tra xem trong danh sách đã có mặt hàng này chưa. Nếu có thì ko cho add nữa
                for (int i = 0; i < n; i++)
                {
                    if (f.Item_ID == Convert.ToInt32(dgvList1.Rows[i].Cells["Item_ID"].Value))
                    {
                        return;
                    }
                }
                //Sau khi kiểm tra xong, nếu được làm tiếp thì sẽ add vào danh sách như sau:
                dgvList1.Rows.Insert(n, 1);
                dgvList1.Rows[n].Cells["RowNumber"].Value = n + 1;
                dgvList1.Rows[n].Cells["Item_ID"].Value = f.Item_ID;
                dgvList1.Rows[n].Cells["Item_Code"].Value = f.Item_Code;
                dgvList1.Rows[n].Cells["Item_Name"].Value = f.Item_Name;
                dgvList1.Rows[n].Cells["CalculationUnit_Name"].Value = f.Unit_Name;

                dgvList1.Rows[n].Cells["Quantity"].Value = 1;
                dgvList1.Rows[n].Cells["Price"].Value = f.Item_PurchasePrice.ToString("#,##0");
                dgvList1.Rows[n].Cells["DownPrice"].Value = "0.0";
                dgvList1.Rows[n].Cells["VAT"].Value = 0;

                dgvList1.Rows[n].Cells["Total"].Value = f.Item_PurchasePrice.ToString("#,##0");
                // Cho sửa chữa dữ liệu trên datagridview tại các ô của cột Quantity, Price, DownPrice, VAT
                dgvList1.BeginEdit(false);
                dgvList1.CurrentCell = dgvList1.Rows[n].Cells["Quantity"];
                TotalRowsPrice();
                dgvList1.BeginEdit(true);
                keyword = f.TuKhoa;
            }
        }
        private void TotalRowsPrice()
        {
            decimal gia = 0, giamgia = 0, thue = 0, tongtien = 0;
            tongtien = Convert.ToDecimal(txtRemaining.Text);

            for (int i = 0; i < dgvList1.Rows.Count; i++)
            {
                gia += Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value) * Convert.ToDecimal(dgvList1.Rows[i].Cells["Quantity"].Value);
                giamgia += Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value) * Convert.ToDecimal(dgvList1.Rows[i].Cells["Quantity"].Value) * Convert.ToDecimal(dgvList1.Rows[i].Cells["DownPrice"].Value) / 100;
                thue += Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value) * Convert.ToDecimal(dgvList1.Rows[i].Cells["Quantity"].Value) * Convert.ToDecimal(dgvList1.Rows[i].Cells["VAT"].Value) / 100;
                tongtien += Convert.ToDecimal(dgvList1.Rows[i].Cells["Total"].Value);
            }
            txtTotalPrice.Text = gia.ToString("#,##0");
            txtTotalDownPrice.Text = giamgia.ToString("#,##0");
            txtTotalVAT.Text = thue.ToString("#,##0");
            txtTotal.Text = tongtien.ToString("#,##0");

            txtTotalDeBit.Text = Convert.ToDecimal((Convert.ToDecimal(txtDebit.Text) + tongtien)).ToString("#,##0");

        }
        private decimal TotalColomnPrice(decimal price, int quantity, decimal downprice, decimal vat)
        {
            decimal giam, thue, gia_sau_khi_giam, total; ;

            giam = price * downprice / 100;
            gia_sau_khi_giam = price - giam;
            thue = price * vat / 100;

            total = (gia_sau_khi_giam + thue) * quantity;
            return total;
        }
        private void dgvList1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

            int newInteger;
            decimal newDecimal;
            if (e.ColumnIndex == dgvList1.Columns["Quantity"].Index)
            {
                if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger <= 0)
                {
                    e.Cancel = true;
                    MessageBox.Show("Số lượng phải là số nguyên dương! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            if (e.ColumnIndex == dgvList1.Columns["Price"].Index)
            {
                if (!decimal.TryParse(e.FormattedValue.ToString(), out newDecimal) || newDecimal < 0)
                {
                    e.Cancel = true;
                    MessageBox.Show("Đơn giá phải là số dương! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            if (e.ColumnIndex == dgvList1.Columns["DownPrice"].Index)
            {
                if (!decimal.TryParse(e.FormattedValue.ToString(), out newDecimal) || newDecimal < 0)
                {
                    e.Cancel = true;
                    MessageBox.Show("Giảm giá phải là số dương! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            if (e.ColumnIndex == dgvList1.Columns["VAT"].Index)
            {

                if (!decimal.TryParse(e.FormattedValue.ToString(), out newDecimal) || newDecimal < 0)
                {
                    e.Cancel = true;
                    MessageBox.Show("VAT phải là số dương! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        private void dgvList1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == dgvList1.Columns["Price"].Index)
            {
                decimal d = decimal.Parse(e.Value.ToString());
                e.Value = d.ToString("#,##0");
            }
            if (e.ColumnIndex == dgvList1.Columns["DownPrice"].Index)
            {
                decimal d = decimal.Parse(e.Value.ToString());
                e.Value = d.ToString("N");
            }
        }
        private void dgvList1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int quantity;
            decimal price, downprice, vat, total;
            quantity = Convert.ToInt32(dgvList1.Rows[e.RowIndex].Cells["Quantity"].Value);
            price = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["Price"].Value);
            downprice = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["DownPrice"].Value);
            vat = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["VAT"].Value);

            total = TotalColomnPrice(price, quantity, downprice, vat);

            dgvList1.Rows[e.RowIndex].Cells["Total"].Value = total.ToString("#,##0");

            TotalRowsPrice();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValid())
                return;
            TotalRowsPrice();
            FormToInfo();
            ReceiptDetailsInfo[] tracks = ReadReceiptDetails();
            if (tracks == null)
            {
                MessageBox.Show("Chưa có mặt hàng nào được chọn! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            receiptinf.Receipt_ID = ReceiptDB.Insert(receiptinf);
            if (receiptinf.Receipt_ID > 0)
            {
                for (int i = 0; i < tracks.Length; i++)
                {
                    tracks[i].ReceiptDetails_ReceiptID = receiptinf.Receipt_ID;
                    if (ReceiptDetailsDB.Insert(tracks[i]) > 0)
                    {
                        Program.taskbarNotifier.Show(Message.Info, Message.Create_Complete, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                        dlgResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        Program.taskbarNotifier.Show(Message.Info, Message.Create_Error, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                        dlgResult = DialogResult.Cancel;
                    }
                }
            }
            else
            {
                Program.taskbarNotifier.Show(Message.Info, Message.Create_Error, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                dlgResult = DialogResult.Cancel;
            }

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (receiptinf.Receipt_ID == 0)
            {
                MessageBox.Show("Cần phải lưu dữ liệu trước khi in.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            frmReport f = new frmReport("PHIEU NHAP HANG", new string[] { receiptinf.Receipt_ID.ToString(), "Phiếu nhập hàng" });
            f.Show();
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmReceipt_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = dlgResult;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            receiptinf.Receipt_ID = 0;
            lblNo.Text = UISetting.AutoFillReceiptCode();
            mtxReceiptDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            lblProvider.Text = "???";
            lblProvider.Tag = 0;
            txtSender.Text = "";
            dgvList1.Rows.Clear();
            TotalRowsPrice();
        }

        private void frmReceipt_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control && !dgvList1.Focused)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.F3:
                    if(receiptinf.Receipt_ID==0)
                    btnSave_Click(null, null);
                    break;
                case Keys.F7:
                    btnPrint_Click(null, null);
                    break;
                case Keys.Escape:
                    
                    this.DialogResult = dlgResult;
                    this.Close();
                    break;
            }
        }

        private void btnNewSpend_Click(object sender, EventArgs e)
        {
            if (receiptinf.Receipt_ID > 0)
            {
                Form fS = new frmSpend(0, "");
                fS.ShowDialog();
            }
        }

        private void txtRemaining_Leave(object sender, EventArgs e)
        {
            txtRemaining.Text = UISetting.GetDecimalNo(txtRemaining.Text).ToString("#,##0");
            TotalRowsPrice();
        }

    }
}